package org.jsola.hr.web;

import org.apache.commons.lang3.StringUtils;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.ConfigCodeConstants;
import org.jsola.hr.provider.ISiteConfigProviderService;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.jsola.hr.constant.HrConstants;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author zhr
 */
@RestController("hrExcelTemplateController")
@RequestMapping(HrConstants.API_PATH + "/v1/excel/template")
public class ExcelTemplateController implements IExcelTemplateController {

    @Autowired
    private ISiteConfigProviderService siteConfigProviderService;

    @Override
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadExcelImportTemplate(@RequestParam String templateName) {
        TokenUser tokenUser = UserContext.getUser();

        //有两个导入模板，不同租户的模板的工作性质不同，通过开发参数区分
        String newTemplateName = siteConfigProviderService.selectValueByCode(templateName, tokenUser.getSiteId());
        if (StringUtils.isNotBlank(newTemplateName)) {
            templateName = newTemplateName;
        }

        // 模板文件
        InputStream is = getClass().getClassLoader().getResourceAsStream("excel/" + templateName);
        ParamException.notNull(is, templateName + "模板没有找到");
        // 编码文件名，防止乱码
        String filenames = new String(templateName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE,"application/vnd.ms-excel")
                .body(new InputStreamResource(is));
    }

}
